import { Sidebar } from "./components/Sidebar/Sidebar.js";
import { Navbar } from "./components/Navbar/Navbar.js";
import { PageTitle } from "./components/PageTitle/PageTitle.js";
import { Footer } from "./components/Footer/Footer.js";
import { DomUtils } from "./utils/DomUtils";
import "./components/Footer/CodeScienceFooter.js";
import { createRouter } from "./utils/router/index.js";
import { userService } from "./services/userService.js";
import { HomePage } from "./pages/HomePage/HomePage.js";
import { DashboardsPage } from "./pages/DashboardsPage/DashboardsPage.js";
import { WebElementsPage } from "./pages/WebElementsPage/WebElementsPage.js";
import { BaseLayout } from "./pages/Layout/base-layout/BaseLayout.js";
import { routerStore } from "./stores/routerStore";
import { UserPage } from "./pages/UserPage/UserPage.js";
import { RegisterPage } from "./pages/RegisterPage/RegisterPage.js"; //RegisterPage 页面
import { LogInPage } from "./pages/LogInPage/LogInPage.js"; //LogInPage 页面
import { NotFoundPage } from "./pages/NotFoundPage/NotFoundPage.js";
//初始化路由
const router = createRouter({
  mode: "history", // 'history' 或 'hash'
  routes: {
    "/": async () => await renderBasicPage(HomePage),
    "/Home": async () => await renderBasicPage(HomePage),
    "/login": async () => await renderPage(LogInPage),
    "/register": async () => await renderPage(RegisterPage),
    "/Dashboards": async () => await renderBasicPage(DashboardsPage),
    "/WebElements": async () => await renderBasicPage(WebElementsPage),
    "/Users": async () => await renderBasicPage(UserPage),
    "/user/:id": (params) => {
      // DomUtils.replaceElement(footer.render(), ".content-container");
      //DomUtils.renderToContainer(WebElementsPage, "content");
      DomUtils.replaceElement(
        new UserPage(params.id).render(),
        ".content-container"
      );
    },
    "*": () => renderPage(NotFoundPage),
  },
  routerStore: routerStore,
});

async function renderBasicPage(PageClass) {
  const contentDOM = await new BaseLayout().render(PageClass);
  const appRoot = document.getElementById("app");
  appRoot.innerHTML = "";
  if (contentDOM instanceof Node) {
    appRoot.appendChild(contentDOM);
  } else {
    console.error("Invalid contentDOM type:", contentDOM);
    throw new Error("渲染内容必须是有效的DOM节点");
  }
}
async function renderPage(PageClass) {
  const contentDOM = await new PageClass().render();
  const appRoot = document.getElementById("app");
  appRoot.innerHTML = "";
  if (contentDOM instanceof Node) {
    appRoot.appendChild(contentDOM);
  } else {
    console.error("Invalid contentDOM type:", contentDOM);
    throw new Error("渲染内容必须是有效的DOM节点");
  }
}
// 暴露到全局方便测试
window.router = router;
